package com.ruoyi.bom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bom.domain.*;
import com.ruoyi.bom.dto.DishBomLockDTO;
import com.ruoyi.bom.dto.DishBomVerifierDTO;
import com.ruoyi.bom.dto.ProlossDto;
import com.ruoyi.bom.dto.StapAndPriceAndUnitTransfer;
import com.ruoyi.bom.mapper.TqlBomMapper;
import com.ruoyi.bom.mapper.TqlDishBomLogMapper;
import com.ruoyi.bom.mapper.TqlStapProlossMapper;
import com.ruoyi.bom.service.ITqlBomService;
import com.ruoyi.bom.service.ITqlDishBomService;
import com.ruoyi.bom.mapper.TqlDishBomMapper;
import com.ruoyi.bom.service.ITqlMaterialTransUnitService;
import com.ruoyi.bom.service.ITqlStapBaseService;
import com.ruoyi.common.core.constant.CommonUtil;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 86198
* @description 针对表【tql_dish_bom(菜品BOM关系表)】的数据库操作Service实现
* @createDate 2024-01-16 15:39:59
*/
@Service
public class TqlDishBomServiceImpl implements ITqlDishBomService {

    @Resource
    private ITqlBomService tqlBomService;

    @Resource
    private TqlDishBomMapper tqlDishBomMapper;

    @Resource
    private TqlDishBomLogMapper tqlDishBomLogMapper;


    @Resource
    private TqlStapProlossMapper tqlStapProlossMapper;

    @Override
    public List<TqlDishBom> selectTqlDishBomList(Map<String, String> params)
    {

        return tqlDishBomMapper.selectTqlDishBomList(params);
    }

    @Override
    public void insertDishBomLog(Long dishId, String fooName, String operate, Integer operateType) {
        String createdBy = SecurityUtils.getUsername();
        TqlDishBomLog log = new TqlDishBomLog();
        log.setFoodName(fooName);
        log.setDishBomId(dishId);
        log.setOperate(operate);
        log.setOperateType(operateType);
        log.setRemark(operate);
        if (operateType ==1) {
            log.setRemark(operate+"["+fooName+"]");
        }
        log.setCreatedBy(createdBy);
        log.setCreatedTime(new Date());
        tqlDishBomLogMapper.insert(log);
    }

    @Override
    @Transactional
    public int lockBatch(List<DishBomLockDTO> dtoList) {
        int i = 0;
        //创建日志
        for (DishBomLockDTO dto : dtoList) {
            this.insertDishBomLog(dto.getId(), dto.getFoodName(),dto.getIsLock()==1 ? "锁定": "取消锁定",2);
            tqlDishBomMapper.lockBatch(dto.getId(), dto.getIsLock());
            i++;
        }
        return i;
    }

    @Override
    public int verifier(DishBomVerifierDTO dto) {
        String verifier = SecurityUtils.getUsername();
        TqlDishBom entity = new TqlDishBom();
        entity.setId(dto.getId());
        entity.setVerifierStatus(dto.getVerifierStatus());
        entity.setVerifier(verifier);
        entity.setVerifierRefuseReason(dto.getVerifierRefuseReason());
        entity.setVerifierTime(new Date());
        if (dto.getVerifierStatus()==1) {
            entity.setIsLock(1);
        }
        if (dto.getVerifierStatus()==2) {
            entity.setIsLock(0);
            //是否启用  0：表示为未启用 1：表示启用
            entity.setIsEnable(0);
        }
        //创建日志
        this.insertDishBomLog(dto.getId(), dto.getFoodName(),"审批",3);
        return tqlDishBomMapper.updateById(entity);
    }

    @Override
    public List<TqlDishBomLog> selectLogList(String id, Integer type) {
        QueryWrapper<TqlDishBomLog> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_bom_id", id);
        wrapper.eq("operate_type", type);
        return tqlDishBomLogMapper.selectList(wrapper);
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<TqlDishBom> selectTqlBomList(Map<String, String> params) {
        return tqlBomService.selectTqlBomList(params);
    }

    @Override
    public void removeById(Long id) {
        tqlDishBomMapper.deleteById(id);
        tqlBomService.deleteBomByDishId(id);
    }

    @Override
    public List<ProlossDto> findProloss(String deptCode, String pandianCode) {
       return tqlStapProlossMapper.findProloss(deptCode,pandianCode);
    }


    @Override
    public void add(TqlDishBom tqlDishBom) {
        Long shopId = 0L;
        if (tqlDishBom.getDeptCode().length() >=17) {
            shopId = tqlDishBomMapper.getShopID(tqlDishBom.getDeptCode().substring(0, 12));
            tqlDishBom.setShopId(shopId);
        }
        tqlDishBomMapper.insert(tqlDishBom);
        Long dishId = tqlDishBom.getId();

        //根据前段传来bom进行记录
        if(!CollectionUtils.isEmpty(tqlDishBom.getBomList())) {
            for (TqlBom bom : tqlDishBom.getBomList()) {
                bom.setDishId(dishId);
                bom.setFoodCode(tqlDishBom.getFoodCode());
                bom.setDeptId(tqlDishBom.getDeptId());
                bom.setType(tqlDishBom.getType());
                bom.setDeptCode(tqlDishBom.getDeptCode());
                bom.setShopId(shopId);
                if (bom.getInitPrice() ==null) {
                    bom.setInitPrice(bom.getPrice());
                }
                bom.setPrice(bom.getInitPrice());
            }
            tqlBomService.insertBatchBom(tqlDishBom.getBomList());
        }
        List<String> foodNames = tqlDishBom.getBomList().stream().map(TqlBom::getStapName).collect(Collectors.toList());
        for (String foodName : foodNames) {
            //创建日志
            this.insertDishBomLog(dishId, foodName,"新增",1);
        }
    }

    @Override
    public TqlDishBom getById(Long id) {

        TqlDishBom entity = tqlDishBomMapper.selectById(id);
        List<TqlBom> bomList = tqlBomService.selectTqlBomById(id);
        List<StapAndPriceAndUnitTransfer> newList=new ArrayList<>();
        for(TqlBom bom:bomList)
        {

            StapAndPriceAndUnitTransfer sp=  getBomEntity(bom.getStapCode(),bom.getDeptCode());
            sp.setQuota(bom.getQuota());
            sp.setPrice(bom.getPrice());
            sp.setCost(bom.getCost());
            sp.setBomId(bom.getId());
            newList.add(sp);
        }



entity.setSput(newList);

//        entity.setBomList(bomList);
        return entity;
    }
    @Autowired
    private ITqlStapBaseService tqlStapBaseService;
    @Autowired
    private ITqlMaterialTransUnitService tqlMaterialTransUnitService;
    private StapAndPriceAndUnitTransfer getBomEntity(String stapCode1,String deptCode) {
        StapAndPriceAndUnitTransfer result=new StapAndPriceAndUnitTransfer();
        TqlStapBase base=tqlStapBaseService.getStapBaseByStapCode(stapCode1);
        result.setBase(base);
// base
        int state=0;
        String[] unitArr=new String[]{"千克","克","KG","KG1"};
        String baseUnit=base.getStapBaseUnit();

        boolean isInUnitArr = Arrays.asList(unitArr).contains(baseUnit);
        //----------------------------------------
        //第一种情况 是标准单位
        if(isInUnitArr)
        {
            base.setStapAuxUnit(baseUnit);
            state=1;
        }
        else{
            String auxUnit=base.getStapAuxUnit();
            if(!StringUtils.isEmpty(auxUnit))//有辅助段位
            {

                TqlMaterialTransUnit unit= tqlMaterialTransUnitService.selectTqlMaterialTransUnitByFMaterialIdfnumber(stapCode1);
                if(null!=unit)
                {
                    state=2;
                    result.setMt(unit);
                }
                else
                {
                    if(baseUnit.equals(auxUnit))
                    {
                        state=5;
                    }
                    else {
                        state=3;
                    }

                }



            }else{
                state=4;
            }
        }
        //----------------------------------------
        result.setFlag(state);
        return result;
    }

    @Override
    public void updateById(TqlDishBom tqlDishBom) {
        //修改dish_bom表
        tqlDishBom.setUpdatedTime(new Date());
        tqlDishBomMapper.updateById(tqlDishBom);
        Long shopId = 0L;
        if (tqlDishBom.getDeptCode().length() >=17) {
            shopId = tqlDishBomMapper.getShopID(tqlDishBom.getDeptCode().substring(0, 12));
            tqlDishBom.setShopId(shopId);
        }
        //先执行删除逻辑
        for(TqlBom tqlBom : tqlDishBom.getBomList()) {
            //用bomid查询 select count(1) from tql_bom where id=#{bomId}
            Integer flag = tqlBom.getFlag();
            tqlBom.setDishId(tqlDishBom.getId());
            tqlBom.setFoodCode(tqlDishBom.getFoodCode());
            tqlBom.setFoodCode(tqlDishBom.getFoodCode());
            tqlBom.setDeptId(tqlDishBom.getDeptId());
            tqlBom.setType(tqlDishBom.getType());
            tqlBom.setDeptCode(tqlDishBom.getDeptCode());
            tqlBom.setShopId(shopId);
            if(null==flag) {
                tqlBomService.updateOrInsertTqlBom(tqlBom);
                //创建日志
                if (tqlBom.getId() !=null) {
                    this.insertDishBomLog(tqlDishBom.getId(), tqlBom.getStapName(),"新增",1);
                }else {
                    this.insertDishBomLog(tqlDishBom.getId(), tqlBom.getStapName(),"修改",1);
                }
            }else if(1==flag) {
                tqlBomService.deleteTqlBomById(tqlBom.getId());
                //创建日志
                this.insertDishBomLog(tqlDishBom.getId(), tqlBom.getStapName(),"删除",1);
            }

        }
    }

    @Override
    public int checkFoodExistDish(Long id, String foodCode) {
        return tqlDishBomMapper.checkFoodExistDish(id, foodCode);
    }

}




